package com.itheima.reggie.controller;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.druid.util.StringUtils;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.SmsTemplate;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

//进店客户
@RestController
@Slf4j
public class UserController {

    @Autowired
    private HttpSession httpSession;

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private HttpSession session;

    //发送短信验证码
    @PostMapping("/user/sendMsg")
    public ResultInfo sendMsg(@RequestBody Map<String, String> map) {


        //1.接收参数
        String phone = map.get("phone");
        //2.生成验证码
        //String code = RandomUtil.randomNumbers(6);
        //todo 写死一个验证码为123  为了测试方便
        String code = "123";
        log.info("生成的验证码为:{}", code);

        //3.将验证码保存到session中
        httpSession.setAttribute("SMS_" + phone, code);

        //todo 测试成功之后，先注释掉
        //4.发送验证码到手机
        //smsTemplate.sendSms(phone, code);

        return ResultInfo.success(null);


    }

    //用户登录注册
    @PostMapping("/user/login")
    public ResultInfo login(@RequestBody Map<String, String> map) {
        //1.接收参数
        String phone = map.get("phone");
        String code = map.get("code");

        //2.效验code，前端传入 code vs session保存code
        String codeFromSession = (String) httpSession.getAttribute("SMS_" + phone);
        if (!StringUtils.equals(code, codeFromSession)
                || StringUtils.isEmpty(code)
                || StringUtils.isEmpty(codeFromSession)) {
            return ResultInfo.error("验证码不对");
        }

        //根据phone从数据库中查询
        User user = userService.findByPhone(phone);
        if (user != null) {
            //3-1 差到了，代表的是老用户在登录
        } else {
            //3-2 没查到，代表新用户在注册
            user = new User();

            user.setPhone(phone);
            user.setStatus(1);//激活
            userService.save(user);
        }

        //4.将user信息保存到session中(注意：这个键必须跟拦截器中使用的键一致)
        httpSession.setAttribute("SESSION_USER", user);

        //5.返回成功标识(注意不要忘记返回user，前端需要使用)
        return ResultInfo.success(user);

    }

    /**
     * 退出登录
     */
    @PostMapping("/user/logout")
    public ResultInfo logout() {
        //1.注销session
        session.invalidate();

        //2.返回登录成功结果
        return ResultInfo.success(null);
    }

}
